const App = getApp()
import { SpecialModel } from '../../models/special.js'
const ModeSpecial = new SpecialModel()
import { AppModel } from '../../models/app.js'
const ModelApp = new AppModel()
import { ManagerModel } from '../../models/manager'
const managerModel = new ManagerModel()
import { HomeModel } from '../../models/home.js'
const ModelHome = new HomeModel()
import { random, domInter } from '../../utils/index.js'
import { formatDate } from '../../utils/index'
Page({
  data: {
    isLogined: true,
    scode: '',
    bossid: '',
    specialInfo: {}, // 专场信息
    goodsList: null, // 商品列表
    pageList: [], // 热点图
    pageIndex: 1, // 起始页
    pageSize: 20, // 分页数量
    loading: false, // 正在加载
    hasNext: true, // 是否有下一页
    type: 0, // 请求数据类型
    priceState: 0, //搜索条件-价格状态
    discountState: 0, //搜索条件-折扣状态
    screeningState: 0, //搜索条件-筛选
    empty: false,
    iphoneX: App.globalData.isIphoneX,
    activityEnd: false,
    carNum: 0,
    loadDone: false,
    showShare: false,
    shareData: {},
    floorstatus: false, // 返回顶部
    showCanvas: false,
    template: {},
    //  isBack: false,
    query: [],
    showType: '',
    userType: '',
    more: '',
    guideVisible: false,
    guideInfo: {},
    wiggle: true,
    userFansType: '',
    showCard: false,
    statusBarHeight: App.globalData.statusBarHeight,
    isTabbar: false,
    navigationBarTitle: '',
    minBanner: [],
    isFixed: false, // 吸顶
    top: 0, // 距离顶部距离
    scrollTop: 0,
    selected: [], //筛选记录
    filterItems: [], // 筛选项
    filterIn: false, //显示筛选
    isFisrt: true,
    showGuide: false
  },
  onLoad: function(options) {
    console.log('activity onLoad==', options)
    // 扫码二维码进入 encodeURIComponent
    if (options.scene) {
      let scene = decodeURIComponent(options.scene)
      //&是我们定义的参数链接方式
      this.data.bossid = scene.split('&')[0]
      this.data.scode = scene.split('&')[1]
    } else {
      // 好友链接或上个页面进入
      this.data.bossid = options.bossid // 分享人id
      this.data.scode = options.scode // 专场编码
      // this.data.query = options.query ? options.query : [] // 搜索条件
    }

    //通过路由判断当前是否存在上一级页面，不存在则不显示返回按钮
    const pages = getCurrentPages()
    if (pages.length <= 1) {
      this.setData({
        isTabbar: true
      })
    }
    // 存储bossid
    wx.setStorageSync('bossid', this.data.bossid)
    // 初始化
    this.init()
    // 获取环境变量
    //  this.queryEnv()
    // 隐藏右上角分享功能
    wx.hideShareMenu()
  },
  onShow: function() {
    // 搜索返回
    // if (this.data.isBack) {
    //   // 回到tabbar位置
    //   // this.backTabbar()
    //   // 设置query用于回显,其他重置
    //   this.setData({
    //     query: this.data.query,
    //     priceState: 0,
    //     discountState: 0,
    //     type: 0
    //   })
    //   // 重置吸顶
    //   this.onScroll()
    //   this.loadMore(true)
    // }
    // 重置吸顶
    // this.onScroll()
    // 统计数据
    App.globalData.gio('setPage', {
      AcTitle: '专场页',
      AcCode: this.data.scode // 专场编码
    })
    this.setGio()
  },
  // 统计
  setGio() {
    let info = this.data.specialInfo
    // 没有请求到数据的时候不统计
    if (!info.specialName) {
      return
    }
    App.globalData.gio('setPage', {
      AcTitle: '专场页',
      AcCode: this.data.scode, // 专场编码
      AcDate: formatDate(info.startDate, 'yyyy/MM/dd'), // 开场时间
      AcName: info.specialName // 专场名称
    })
  },

  // 获取到顶部的高度,在页面渲染之后
  getDomClientRect() {
    let _this = this
    setInterval(() => {
      domInter('#top-container', _this).then(rect => {
        _this.setData({
          top: rect.height
        })
      })
    }, 300)
  },
  // 登陆成功，由login组件触发
  loginSuccess() {
    this.setData({
      isLogined: true
    })
    // 成功后操作
    // 获取详情
    this.loadMore(true)
    //获取购物车数量
    this.selectCartNumber()
    // 获取粉丝
    this.getFans()
    //获取上一页
    this.getPrePage()
  },
  // 用户登录
  init() {
    const _this = this
    App.getVipInfo(function(userInfo) {
      if (!userInfo) {
        console.log('没有token,获取用户信息失败')
        _this.setData({
          isLogined: false
        })
        // 有用户信息了可以正常请求数据
      } else {
        // 获取详情
        _this.loadMore(true)

        //获取购物车数量
        _this.selectCartNumber()
        // 获取粉丝
        _this.getFans()
        //获取上一页
        _this.getPrePage()
      }
    })
  },

  //检测上一页
  getPrePage() {
    const that = this
    const pages = getCurrentPages()
    // const currPage = pages[pages.length - 1]; //当前页面
    // const prevPage = pages[pages.length - 2]; //上一个页面
    // console.log(pages)
    if (pages.length == 1) {
      that.setData({
        isTabbar: true
      })
    }
  },
  // 吸顶
  onScroll() {
    const { top, scrollTop } = this.data
    const isFixed = scrollTop >= top
    if (isFixed !== this.data.isFixed) {
      this.setData({
        isFixed
      })
    }
  },
  onPageScroll: function(res) {
    // 获取 滚动高度
    let _this = this
    const wHight = App.globalData.mobile.windowHeight
    this.data.scrollTop = res.scrollTop
    // 吸顶
    _this.onScroll()
    // 滚动大于屏幕高度
    if (this.data.scrollTop > wHight && !_this.data.floorstatus) {
      _this.setData({
        floorstatus: true
      })
    } else if (this.data.scrollTop < wHight && _this.data.floorstatus) {
      _this.setData({
        floorstatus: false
      })
    }
  },
  // 推荐专场小轮播
  getRecommend() {
    const self = this
    const params = {}
    ModelHome.queryCrazy()
      .then(res => {
        self.setData({
          activityEnd: true,
          minBanner: res.data.classList // 小轮播
        })
      })
      .catch(err => {})
  },

  // 点击按照价格排序
  onPriceSort() {
    // 0:默认排序，1：价格升序 2:价格降序 3：折扣升序 4：折扣降序
    var priceState = this.data.priceState
    if (priceState == 0) {
      priceState = 1
    } else if (priceState == 1) {
      priceState = 2
    } else if (priceState == 2) {
      priceState = 0
    }
    this.setData({
      priceState: priceState,
      discountState: 0,
      type: priceState,
      query: []
    })
    this.loadMore(true)
  },
  // 点击按照销量排序
  onSaleSort() {
    var discountState = this.data.discountState
    if (discountState == 0) {
      discountState = 3
    } else if (discountState == 3) {
      discountState = 4
    } else if (discountState == 4) {
      discountState = 0
    }
    this.setData({
      priceState: 0,
      discountState: discountState,
      type: discountState,
      query: []
    })
    this.loadMore(true)
  },
  // 删除筛选条件
  goDelFilter() {
    // 设置删除后的回显,单选全部flase即可，后期多选可能要改
    this.data.searchItems.map(n => {
      n.stringList.map((m, index) => {
        m.checked = false
      })
    })
    this.setData({
      query: [],
      searchItems: this.data.searchItems
    })
    this.loadMore(true)
  },
  //加载更多
  loadMore(reload) {
    if (reload) {
      this.setData({
        pageIndex: 1,
        hasNext: true
      })
    }
    if (this.data.loading || !this.data.hasNext) {
      return
    }
    this.setData({
      loading: true
    })
    const params = {
      specialCode: this.data.scode,
      type: this.data.type,
      pageIndex: this.data.pageIndex,
      pageSize: this.data.pageSize
    }
    // 如果有搜索条件则追加
    if (this.data.query && this.data.query.length > 0) {
      params.specNameArr = this.data.query.map(m => encodeURIComponent(m.value))
      params.userType = this.data.userType
      ModeSpecial.getSpecialBySize(params)
        .then(res => {
          // 如果重新/第一次加载则清空 goodsList
          if (reload) {
            this.setData({
              goodsList: []
            })
          }
          const tempArray = this.data.goodsList.concat(res.data.goodsList)
          this.setData({
            goodsList: tempArray,
            hasNext: res.data.hasNext,
            loading: false
            //   isBack: false
          })
          wx.stopPullDownRefresh()
        })
        .catch(err => {
          this.setData({
            loading: false
            // isBack: false
          })
        })
    } else {
      // 不通过尺码搜索
      ModeSpecial.getSpecial(params)
        .then(res => {
          // 如果重新/第一次加载则清空 goodsList,设置专场信息
          if (reload) {
            this.setData({
              goodsList: [],
              pageList: res.data.pageList,
              specialInfo: res.data.specialInfo,
              userType: res.data.userType,
              navigationBarTitle: res.data.specialInfo.specialName
            })
            // 筛选项 页面第一次请求的时候加载
            if (this.data.isFisrt) {
              this.filtersItems(res.data.specialInfo.id)
              this.data.isFisrt = false
            }

            // 获取高度
            this.getDomClientRect()
          }
          const tempArray = this.data.goodsList.concat(res.data.goodsList)
          this.setData({
            goodsList: tempArray,
            hasNext: res.data.hasNext,
            loading: false
          })
          this.setGio()
          wx.stopPullDownRefresh()
        })
        .catch(err => {
          wx.stopPullDownRefresh()
          this.setData({
            loading: false
          })
          if (err.status == 400068) {
            // 活动下架，获取推荐专场列表
            this.getRecommend()
          }
        })
    }
  },

  // 访问分享数量接口
  setShareNum(id) {
    ModelApp.addShare({
      specialId: id
    })
      .then(res => {})
      .catch()
  },
  // 点击分享专场
  doShowShare() {
    const shareInfo = this.data.specialInfo
    // 访问分享数量接口
    this.setShareNum(shareInfo.id)
    this.setData({
      showType: 'activity',
      showShare: true,
      shareData: {
        shareTitle: shareInfo.specialName,
        mainImg: shareInfo.mainImg,
        shareImg: shareInfo.shareImg + '?imageMogr2/quality/80',
        startDate: shareInfo.startDate,
        endDate: shareInfo.endDate,
        specialCode: shareInfo.specialCode,
        sharePath: `/pages/activity/index?bossid=${App.globalData.userInfo.userCode}&scode=${shareInfo.specialCode}`
      }
    })
  },
  // 点击触发显示新手指导和新用户直接弹
  emitShowGuide() {
    // 停止晃动
    this.setData({
      wiggle: false
    })
    if (this.data.userType == 1) {
      // this.setData({
      //   guideVisible: true
      // })
      this.doShowShare()
    } else {
      // 其他用户弹出专场分享
      this.doShowShare()
    }
  },
  // 停止分享icon晃动
  doStopWiggle() {
    this.setData({
      wiggle: true
    })
  },
  // 获取粉丝
  getFans() {
    //获取当前用户类型，佣金，粉丝，邀请人信息
    managerModel
      .getFansInfo()
      .then(res => {
        // 获取还有多少粉丝升级
        const guideInfo = res.data
        guideInfo.userImg = App.globalData.userInfo.userImg
        this.setData({
          userFansType: res.data.userType,
          guideInfo: guideInfo
        })
        // if (res.data.userType == 1) {
        //   // 普通用户分享
        //   if (App.globalData.levelFlag) {
        //     this.setData({
        //       showGuide:true
        //     })
        //     App.globalData.levelFlag = false
        //   }
        // }
      })
      .catch(err => {})
  },
  //查看数量
  selectCartNumber() {
    const self = this
    const params = {}
    ModelApp.selectCartNumber(params)
      .then(res => {
        self.setData({
          carNum: res.data.number.liteCart
        })
      })
      .catch(err => {
        console.log(err)
      })
  },
  // 微信到底
  onReachBottom: function() {
    if (this.data.activityEnd) {
      return
    }
    this.data.pageIndex = this.data.pageIndex + 1
    this.loadMore()
  },
  /*分享*/
  onShareAppMessage: function(ops) {
    // 转发只能通过右上角转发
    // const ucode = App.globalData.userInfo.userCode
    // const shareInfo = this.data.specialInfo
    const shareInfo = ops.target.dataset.share
    console.log('activity onShareAppMessage' + shareInfo)
    // 转发活动编码用户编码
    //const path = `/pages/activity/index?bossid=${ucode}&scode=${shareInfo.specialCode}`
    return {
      title: shareInfo.shareTitle,
      path: shareInfo.sharePath,
      imageUrl: shareInfo.shareImg,
      success: function(res) {
        // 转发成功
        console.log('转发成功:' + JSON.stringify(res))
      },
      fail: function(res) {
        // 转发失败
        console.log('转发失败:' + JSON.stringify(res))
      }
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    // 获取详情
    this.loadMore(true)
    this.selectCartNumber()
  },
  // 去筛选
  goFilter() {
    // 筛选进入
    this.setData({
      filterIn: true
    })
    // wx.navigateTo({
    //   url:
    //     '/pages/activity/filter/index?specialId=' +
    //     this.data.specialInfo.id +
    //     '&query=' +
    //     this.data.query
    // })
  },
  // 筛选
  doFilter(e) {
    let selected = e.detail
    this.setData({
      query: selected, // 筛选数组
      priceState: 0, // 重置价格排序
      discountState: 0, // 重置折扣排序
      type: 0, // 重置搜索类型
      filterIn: false
    })
    this.loadMore(true)
  },
  // 筛选项
  filtersItems(id) {
    const _this = this
    ModeSpecial.getGoodsSize({
      specialId: id
    }).then(res => {
      // 重新组装数据
      const searchItems = res.data.sizeList.map(n => {
        return Object.assign({}, n, {
          type: 'radio',
          key: n.key,
          stringList: n.stringList.map((m, index) =>
            Object.assign(
              {},
              {
                checked: _this.data.filterItems.includes(m), // 回显query里有返回true
                value: m,
                label: m,
                id: index
              }
            )
          )
        })
      })
      console.log(searchItems)
      this.setData({
        searchItems: searchItems
      })
    })
  }
})
